package com.wzq.animal.fore.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.animal.back.pojo.User;
import com.wzq.animal.common.Result;
import com.wzq.animal.fore.pojo.AnimalInfo;
import com.wzq.animal.fore.service.AnimalInfoService;
import com.wzq.animal.utils.MyOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/animal")
public class AnimalInfoController {
    @Autowired
    private AnimalInfoService animalInfoService;

    /**
     * 获取动物信息的分页数据（包括搜索功能）
     * @param currentPage
     * @param pageSize
     * @param nameKeywords
     * @return
     */
    @GetMapping("/getAnimalsInfo/{currentPage}/{pageSize}")
    public Result getAnimalsInfo(@PathVariable("currentPage") int currentPage,
                                 @PathVariable("pageSize") int pageSize,
                                 @RequestParam("nameKeywords") String nameKeywords) {
        Page<AnimalInfo> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<AnimalInfo> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(nameKeywords)) {
            queryWrapper.like(AnimalInfo::getName, nameKeywords);
        }
        animalInfoService.page(page, queryWrapper);
        return Result.success(page);
    }

    /**
     * 增加或者修改动物信息
     * @param animalInfo
     * @return
     */
    @PostMapping("/addOrUpdateAnimal")
    public Result addOrUpdateAnimal(@RequestBody AnimalInfo animalInfo) {
        animalInfoService.saveOrUpdate(animalInfo);
        Integer id = animalInfo.getId();
        if(StringUtils.isNotBlank(id.toString())){
            AnimalInfo updatedUser = animalInfoService.getById(id);
            return Result.success(updatedUser);
        }
        return Result.success();
    }

    /**
     * 单个删除
     * @param id
     * @return
     */
    @DeleteMapping("/delAnimal/{id}")
    public Result delAnimal(@PathVariable("id") int id) {
        animalInfoService.removeById(id);
        return Result.success();
    }

    @DeleteMapping("/delAnimalBatch")
    public Result delBatch(@RequestBody List<Integer> ids) {
        animalInfoService.removeByIds(ids);
        return Result.success();
    }

    /**
     *上传动物图片到阿里 OSS
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadAnimal")
    public Result uploadAnimal(@RequestParam MultipartFile file) throws IOException {
        String url = MyOSSUtils.uploadFile(file, "animalsImg");
        return Result.success(url);
    }

    /**
     * 导出表单中的动物信息到本地（excel）
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/export")
    public Result exportUsers(HttpServletResponse response) throws IOException {
        //从数据库中查询所有数据
        List<AnimalInfo> animals = animalInfoService.list();
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(animals, true);
        //设置浏览器的响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("陕西省珍稀动物表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
        return Result.success();
    }

    /**
     * 导入动物信息
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Result importUsers(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<AnimalInfo> animals = reader.readAll(AnimalInfo.class);
        System.out.println(animals);
        animalInfoService.saveBatch(animals);
        return Result.success();
    }
}
